using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Services;

namespace FreeLancer.HRB.WebApp.UserControls
{
  public partial class CommentPane : System.Web.UI.UserControl
  {
    private Guid _postId = Guid.Empty;
    public Guid PostId
    {
      get { return _postId; }
      set { _postId = value; }
    }

    public bool IsCommentAllowed
    {
      get { return divPostComment.Visible; }
      set { divPostComment.Visible = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      PostCommentDataSource.Parameters.Clear();
      PostCommentDataSource.Parameters.Add("PostId", _postId.ToString());
    }

    private PostComment GetPostComment()
    {
      PostComment postComment = null;
      if (!(string.IsNullOrEmpty(txtContent.Text) || string.IsNullOrEmpty(txtName.Value)))
      {
        postComment = new PostComment();
        postComment.PostCommentId = Guid.NewGuid();
        postComment.Author = txtName.Value;
        postComment.CommentDate = DateTime.Now;
        postComment.Address = txtAddress.Value;
        postComment.Comment = txtContent.Text;
        postComment.IsApproved = true;
        postComment.PostId = _postId;
      }

      return postComment;
    }

    private void ClearInformation()
    {
      txtName.Value = string.Empty;
      txtContent.Text = string.Empty;
      txtAddress.Value = string.Empty;
    }

    protected void btnSend_OnClick(object sender, EventArgs e)
    {
      try
      {
        PostComment comment = GetPostComment();
        using (ConnectionScope.CreateTransaction())
        {
          GlobalCache.PostCommentServiceInstance.Save(comment);
          bool success = ConnectionScope.Complete();
          if (!success)
          {
            LoggingService.LogCritical("CommentPane Control",
              "Complete transaction failed when saving PostComment",
              null, LoggingService.DefaultCategory, true);
          }
          else
            ClearInformation();
        }

        PostCommentRepeater.DataBind();
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("CommentPane Control", "Exception when save PostComment",
            ex, LoggingService.DefaultCategory, true);
      }
    }
  }
}